<?php
include 'utilities.php';
include 'crawl.php';
Utititles::includeClasses();

$crawl = new Crawl();
$tb_sources = new Tb_Game_Sources();
$sources = $tb_sources->get();

$tb_games = new Tb_Games();
$tb_club = new Tb_Clubs();

// Crawl
foreach ($sources AS $source) {
    for ($i = $source['start']; $i <= $source['end']; $i++) {
        $url = vsprintf($source['url'], array($i, $i));
        $data = $crawl->getPage($url);
        $matches = $crawl->parseData($data, $source['pattern']);
        //1: date 18/12/2012 2
        //2: First club
        //3: Result
        //4: First half
        //5: Second club
        if ($matches[1]) {
            $index = 0;
            foreach ($matches[1] as $val) {
                // Date
                $datetime = DateTime::createFromFormat( 'd/m/Y H:i', $val);
                $timestamp = $datetime->getTimestamp();

                // First club
                $name1 = $matches[2][$index];
                $club1 = $tb_club->get($name1);

                // Result
                $goal = $matches[3][$index];
                $balls = explode('-', $goal);

                // First half balls
                $half_goal = $matches[4][$index];
                $first_half_balls = explode('-', $half_goal);

                // Second club
                $name2 =$matches[5][$index];
                $club2 = $tb_club->get($name2);

                $params = array(
                    'date'  =>  $timestamp,
                    'id_tour' => $source['id_tour'],
                    'id_club1' => $club1['id'],
                    'id_club2' => $club2['id'],
                    'club1_scores' => trim($balls[0]),
                    'club2_scores' => trim($balls[1]),
                    'first_half_club1_scores' => trim($first_half_balls[0]),
                    'first_half_club2_scores' => trim($first_half_balls[1]),
                    'round' =>  $i,
                    'club1_name'    =>  $name1,
                    'club2_name'    =>  $name2,
                    'season'    => $source['season']
                );
                
                $tb_games->insert($params);
                //$tb_sources->updateStatus($source['id']);
                $index++;
                echo $index."\n";
            }
        }
    }
}